package com.erp.dao.impl;

import com.erp.bean.CommodityType;
import com.erp.dao.CommodityTypeDao;
import com.erp.util.db.DataBaseDao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zch
 * 商品类型数据访问实现类
 */
public class CommodityTypeDaoImpl extends DataBaseDao implements CommodityTypeDao {
    @Override
    public List<CommodityType> findAll() {
        List<CommodityType> list = new ArrayList<>();
        try {
            //获取数据库连接对象
            buildConnection();
            String sql = "select `tyid`,`tyname` from CommodityType";
            pstmt = conn.prepareStatement(sql);
            rs = pstmt.executeQuery();
            while (rs.next()){
                CommodityType commodityType = new CommodityType(rs.getInt(1),rs.getString(2));
                list.add(commodityType);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close();
        }
        return list;
    }

    @Override
    public CommodityType findByentid(int tyid) {
        CommodityType commodityType = null;
        try {
            //获取数据库连接对象
            buildConnection();
            String sql = "select * from commoditytype where tyid = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,tyid);
            rs = pstmt.executeQuery();
            while (rs.next()){
                commodityType = new CommodityType(rs.getInt(1),rs.getString(2));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close();
        }
        return commodityType;
    }

    @Override
    public int update(CommodityType commodityType) {
        int i = 0;
        try {
            //获取数据库连接对象
            buildConnection();
            String sql = "update commoditytype set tyname = ? where tyid = ?";
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,commodityType.getTyname());
            pstmt.setInt(2,commodityType.getTyid());
            i = pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close();
        }

        return i;
    }

    @Override
    public int addCommodityType(CommodityType commodityType) {
        int i = 0;
        try {
            //获取数据库连接对象
            buildConnection();
            String sql = "insert into commoditytype (tyid,tyname) values (?,?)";
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1,commodityType.getTyid());
            pstmt.setString(2,commodityType.getTyname());
            i = pstmt.executeUpdate();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            close();
        }
        return i;
    }
}
